package com.retrofit.demo.api;

import com.breeze.toolkit.retrofit.HostSelectionInterceptor;
import com.breeze.toolkit.retrofit.OkHttpClientInterceptor;
import com.squareup.okhttp.OkHttpClient;

import java.util.concurrent.TimeUnit;

import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;

/**
 * Created by john on 2016/8/23.
 */
public enum RetrofitEnum {
	INSTANCE;

	private APIService mAPIService;
	private OkHttpClientInterceptor mOkHttpClientInterceptor;
	private HostSelectionInterceptor mHostSelectionInterceptor;
	private Retrofit mRetrofit;

	RetrofitEnum() {
		OkHttpClient okHttpClient = new OkHttpClient();
		okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
		okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
		okHttpClient.setWriteTimeout(60, TimeUnit.SECONDS);
		okHttpClient.interceptors().add(mOkHttpClientInterceptor = new OkHttpClientInterceptor());
		okHttpClient.interceptors().add(mHostSelectionInterceptor = new HostSelectionInterceptor());

		mRetrofit = new Retrofit.Builder()
				.baseUrl(APIService.HOST)
				.client(okHttpClient)
				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
				.addConverterFactory(GsonConverterFactory.create())
				.build();

		mAPIService = mRetrofit.create(APIService.class);
	}

	public void setConnectTimeout(int timeout) {
		mRetrofit.client().setConnectTimeout(timeout, TimeUnit.SECONDS);
	}

	public void setReadTimeout(int timeout) {
		mRetrofit.client().setReadTimeout(timeout, TimeUnit.SECONDS);
	}

	public void setWriteTimeout(int timeout) {
		mRetrofit.client().setWriteTimeout(timeout, TimeUnit.SECONDS);
	}

	public static APIService getAPIService() {
		return RetrofitEnum.INSTANCE.mAPIService;
	}

	public static OkHttpClientInterceptor getInterceptor() {
		return RetrofitEnum.INSTANCE.mOkHttpClientInterceptor;
	}

	public static HostSelectionInterceptor getHostSelectionInterceptor() {
		return RetrofitEnum.INSTANCE.mHostSelectionInterceptor;
	}
}
